
var load_upload_image1 = load_upload_image2 = load_upload_image3 = load_upload_image4 = load_upload_image5 = load_upload_image6 = true;
var load_upload_video = true;
var load_upload_image1_arr = [],
    load_upload_image2_arr = [],
    load_upload_image3_arr = [],
    load_upload_image4_arr = [],
    load_upload_image5_arr = [],
    load_upload_image6_arr = [];


var Customhome = function() {

    var defaultOperation = '<button type="button" class="btn blue edit-btn">修改</button><button type="button" class="btn red delete-btn">删除</button>';

    // HTML模板
    // 轮播图
    var adbannerTemp = stringLines(function(){/*
	<tr >
		<td>
            <div class="">
                <div id="upload-image">
                    <span id="upload-btn" data-multi="false">
                        <div class="exist-img" style="width: 100%;">
                            <input type="hidden" class="form-control" data-required="1" name="imgUrl" value="">
                            <img src="/public/static/admin/img/default.png" alt="图片上传" style="width: 200px;height: 100px;" />
                        </div>
                    </span>
                </div>
                <span class="help-block"> (建议尺寸：750*360) </span>
            </div>
	    </td>
	    <td>
		    <select class="form-control select-links" name="linkType">
                <option value="0" selected>无链接</option>
                <option value="1">头条</option>
                <option value="41">头条详情</option>
                <option value="2">村子</option>
                <option value="42">村子详情</option>
                <option value="5">乡镇机关</option>
                <option value="6">农事知识</option>
                <option value="25">知识分类</option>
                <option value="43">知识列表</option>
                <option value="44">知识详情</option>
                <option value="8">特色专题</option>
                <option value="45">特色专题列表</option>
                <option value="46">特色专题详情</option>
                <option value="9">党务公示</option>
                <option value="47">党务公示详情</option>
                <option value="10">党建要闻</option>
                <option value="48">党建要闻分类</option>
                <option value="49">党建要闻详情</option>
                <option value="11">党课学习</option>
                <option value="50">党课分类</option>
                <option value="12">考试测评</option>
                <option value="14">投票调研</option>
                <option value="15">组织活动</option>
                <option value="16">扶贫动态</option>
                <option value="17">扶贫项目</option>
                <option value="19">一村一品</option>
                <option value="51">产品分类</option>
                <option value="52">产品详情</option>
                <option value="21">便民服务</option>
                <option value="22">智慧党建</option>
                <option value="23">精准扶贫</option>
                <option value="24">产地直供</option>
            </select>
            <input type="hidden" name="linkCateId" value="" />
	        <input type="hidden" name="linkId" value="" />
	        <input type="hidden" name="displayName" value="" />
	    </td>
	    <td>
            <input type="number" class="form-control" min="1" name="sorting" value="1" />
	    </td>
	    <td>
	        <input type="hidden" name="componentId" value="" />
            <button type="button" class="btn blue save-btn">保存</button>
            <button type="button" class="btn default cancle-btn">取消</button>
	    </td>
	</tr>
*/});
    // 自适应图片
    var adaptImgTemp = stringLines(function(){/*
	<tr >
		<td>
            <div class="">
                <div id="upload-image">
                    <span id="upload-btn" data-multi="false">
                        <div class="exist-img" style="width: 100%;">
                            <input type="hidden" class="form-control" data-required="1" name="imgUrl" value="">
                            <img src="/public/static/admin/img/default.png" alt="图片上传" style="width: 200px;height: 100px;" />
                        </div>
                    </span>
                </div>
            </div>
	    </td>
	    <td>
		    <select class="form-control select-links" name="linkType">
                <option value="0" selected>无链接</option>
                <option value="1">头条</option>
                <option value="41">头条详情</option>
                <option value="2">村子</option>
                <option value="42">村子详情</option>
                <option value="5">乡镇机关</option>
                <option value="6">农事知识</option>
                <option value="25">知识分类</option>
                <option value="43">知识列表</option>
                <option value="44">知识详情</option>
                <option value="8">特色专题</option>
                <option value="45">特色专题列表</option>
                <option value="46">特色专题详情</option>
                <option value="9">党务公示</option>
                <option value="47">党务公示详情</option>
                <option value="10">党建要闻</option>
                <option value="48">党建要闻分类</option>
                <option value="49">党建要闻详情</option>
                <option value="11">党课学习</option>
                <option value="50">党课分类</option>
                <option value="12">考试测评</option>
                <option value="14">投票调研</option>
                <option value="15">组织活动</option>
                <option value="16">扶贫动态</option>
                <option value="17">扶贫项目</option>
                <option value="19">一村一品</option>
                <option value="51">产品分类</option>
                <option value="52">产品详情</option>
                <option value="21">便民服务</option>
                <option value="22">智慧党建</option>
                <option value="23">精准扶贫</option>
                <option value="24">产地直供</option>
            </select>
            <input type="hidden" name="linkCateId" value="" />
	        <input type="hidden" name="linkId" value="" />
	        <input type="hidden" name="displayName" value="" />
	    </td>
	    <td class="hide">
            <input type="number" class="form-control" min="1" name="sorting" value="1" />
	    </td>
	    <td>
	        <input type="hidden" name="componentId" value="" />
            <button type="button" class="btn blue save-btn">保存</button>
            <button type="button" class="btn default cancle-btn">取消</button>
	    </td>
	</tr>
*/});
    // 按钮导航
    var buttonNavTemp = stringLines(function(){/*
	<tr >
		<td>
            <div class="">
                <div id="upload-image">
                    <span id="upload-btn" data-multi="false">
                        <div class="exist-img" style="width: 100%;">
                            <input type="hidden" class="form-control" data-required="1" name="imgUrl" value="">
                            <img src="/public/static/admin/img/default.png" alt="图片上传" style="width: 200px;height: 100px;" />
                        </div>
                    </span>
                </div>
            </div>
	    </td>
	    <td>
            <input type="text" class="form-control" min="1" name="displayName" value="" />
	    </td>
	    <td>
		    <select class="form-control select-links" name="linkType">
                <option value="0" selected>无链接</option>
                <option value="1">头条</option>
                <option value="41">头条详情</option>
                <option value="2">村子</option>
                <option value="42">村子详情</option>
                <option value="5">乡镇机关</option>
                <option value="6">农事知识</option>
                <option value="25">知识分类</option>
                <option value="43">知识列表</option>
                <option value="44">知识详情</option>
                <option value="8">特色专题</option>
                <option value="45">特色专题列表</option>
                <option value="46">特色专题详情</option>
                <option value="9">党务公示</option>
                <option value="47">党务公示详情</option>
                <option value="10">党建要闻</option>
                <option value="48">党建要闻分类</option>
                <option value="49">党建要闻详情</option>
                <option value="11">党课学习</option>
                <option value="50">党课分类</option>
                <option value="12">考试测评</option>
                <option value="14">投票调研</option>
                <option value="15">组织活动</option>
                <option value="16">扶贫动态</option>
                <option value="17">扶贫项目</option>
                <option value="19">一村一品</option>
                <option value="51">产品分类</option>
                <option value="52">产品详情</option>
                <option value="21">便民服务</option>
                <option value="22">智慧党建</option>
                <option value="23">精准扶贫</option>
                <option value="24">产地直供</option>
            </select>
            <input type="hidden" name="linkCateId" value="" />
	        <input type="hidden" name="linkId" value="" />
	        <input type="hidden" name="displayName" value="" />
	    </td>
	    <td>
            <input type="number" class="form-control" min="1" name="sorting" value="1" />
	    </td>
	    <td>
	        <input type="hidden" name="componentId" value="" />
            <button type="button" class="btn blue save-btn">保存</button>
            <button type="button" class="btn default cancle-btn">取消</button>
	    </td>
	</tr>
*/});


    var _init = function() {
        // 轮播图
        handle_adbanner();
        // 组合图
        handle_combinationImg();
        // 推荐内容
        handle_recommend();
        // 专题
        //handle_specialtopic();
        // 栏目
        //handle_column();
        // 视频
        handle_vedio();
        // 自适应图片
        handle_adaptImg();
        // 按钮导航
        handle_buttonNav();
        // 分割线
        handle_dividingline();
    };

    var initSortable = function() {
        if (!jQuery().sortable) {
            return;
        }
        $(".sortable").sortable({
            connectWith: ".portlet",
            items: ".portlet",
            opacity: 0.8,
            handle : '.portlet-title',
            coneHelperSize: true,
            placeholder: 'portlet-sortable-placeholder',
            forcePlaceholderSize: true,
            tolerance: "pointer",
            helper: "clone",
            tolerance: "pointer",
            forcePlaceholderSize: !0,
            helper: "clone",
            cancel: ".portlet-sortable-empty, .portlet-fullscreen", // cancel dragging if portlet is in fullscreen mode
            revert: 250, // animation in milliseconds
            update: function(b, c) {
                /*if (c.item.prev().hasClass("portlet-sortable-empty")) {
                    c.item.prev().before(c.item);
                }*/

                // 记录sort后的id名数组
                var idArr = $(".sortable").sortable('toArray', {attribute:'id'});
                //console.log(idArr);
                var param = new Array(idArr.length);
                for(var i=0; i<idArr.length; i++){
                    var element = idArr[i];
                    var frameId = $('#'+element).find("input[name='frameId']").val();
                    param[i] = {
                        'id': frameId,
                        'sorting': i+1
                    };
                }
                $.ajax({
                    url : sort_url,
                    type : 'POST',
                    dataType : 'json',
                    contentType:"application/json; charset=utf-8",
                    data : JSON.stringify(param),
                }).done(function(data) {
                    if (data.code === '1') { // 正确
                        //window.location.reload();
                    }
                });
            },
            stop: function() {
                console.log('move end');
            }
        });
    };

    var initMiniColors = function() {
        $('.mini-colors').each(function() {
            $(this).minicolors({
                control: $(this).attr('data-control') || 'hue',
                defaultValue: $(this).attr('data-defaultValue') || '',
                inline: $(this).attr('data-inline') === 'true',
                letterCase: $(this).attr('data-letterCase') || 'lowercase',
                opacity: $(this).attr('data-opacity'),
                position: $(this).attr('data-position') || 'bottom left',
                change: function(hex, opacity) {
                    if (!hex) return;
                    if (opacity) hex += ', ' + opacity;
                    if (typeof console === 'object') {
                        console.log(hex);
                    }
                },
                theme: 'bootstrap'
            });

        });
    };

    // 轮播图
    var handle_adbanner = function () {
        if($('#applet .adbanner-datatable').length <= 0){
            return;
        }

        $('#applet .adbanner-datatable').each(function(i){
            var top_parent = $(this).parents('.portlet-sortable');
            var sortableId = $(this).parents('.portlet-sortable').attr('id');
            var index = sortableId.substr(8);

            var frameId = top_parent.find('input[name="frameId"]').val();
            var table = $('#adbanner-datatable'+index);

            table.dataTable({
                "processing": false,
                destroy: false,
                serverSide: false, // 关闭服务器模式
                "ajax": {
                    url: componentList_url, // 列表查询
                    data: {'frameId':frameId}
                },
                "autoWidth": false,
                "columns": [
                    {
                        "width": "20%",
                        "data": "imgUrl",
                        "render": function(data, type, row, meta) {
                            return '<img class="center-block" src="'+data+'" style="width: 200px;height: 60px;"/>';
                        }
                    },
                    {
                        "width": "20%",
                        "data": "linkType",
                        "render": function(data, type, row, meta) {
                            return getLinkType(data);
                        }
                    },
                    {"width": "10%","data": "sorting"},
                    {
                        "width": "25%",
                        "data": "null",
                        "defaultContent": defaultOperation
                    }
                ],
                "language": {
                    url: '/public/static/admin/pages/datatable_cn.json'
                },
                "pageLength": 5,
                "order": [
                    [2, "asc"]
                ],
                "columnDefs": [{
                    "orderable": false,
                    "targets": [0, 3]
                }],
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'table_b relative'<'col-md-5'i><'col-md-7'>p>",
                "fnCreatedRow": function(nRow, aData, iDataIndex){
                    // 将第一张图片放到手机相应预览位置
                    if(iDataIndex == 0) {
                        //
                    }
                },
                "fnInitComplete": function() {}
            });

            // 新增或保存
            table.on('click', '.save-btn', function(event) {
                var imgUrl = $("#"+sortableId).find('[name="imgUrl"]').val();
                var displayName = $("#"+sortableId).find('[name="displayName"]').val();
                var sorting = $("#"+sortableId).find('[name="sorting"]').val();
                var linkType = $("#"+sortableId).find('[name="linkType"]').val();
                var linkCateId = $("#"+sortableId).find('[name="linkCateId"]').val();
                var linkId = $("#"+sortableId).find('[name="linkId"]').val();

                var _id = $("#"+sortableId).find('[name="componentId"]').val();
                var frameId = $("#"+sortableId).find('[name="frameId"]').val();// 模块id

                if (!mdTool.validate(imgUrl, 'require')) {
                    layer.msg('请上传图片');
                    return;
                }
                if (!mdTool.validate(linkType, 'require')) {
                    layer.msg('请选择链接类型');
                    return;
                }
                console.log(isRequireLinkId(linkType));
                if (!isRequireLinkId(linkType)){
                    linkCateId = '';
                    linkId = '';
                } else if (!linkId.trim() && !linkCateId.trim()) {
                    layer.msg('请选择弹框信息');
                    return;
                }
                if (!mdTool.validate(sorting, 'num')) {
                    layer.msg('请输入正确的排序');
                    return;
                }

                var param = {
                    'id': _id,
                    'frameId': frameId,
                    'imgUrl': imgUrl,
                    'sorting': sorting,
                    'linkType': linkType,
                    'linkCateId': linkCateId,
                    'linkId': linkId,
                    'displayName': displayName
                };
                var _type = _id == null||_id == '' ? "put" : "post";

                $.ajax({
                    url : saveComponent_url,
                    type : _type,
                    dataType : 'json',
                    contentType:"application/json; charset=utf-8",
                    data : JSON.stringify(param),
                }).done(function(data) {
                    $("#"+sortableId).find('.add-adbanner').prop('disabled', false);
                    if (data.code === '1') {
                        table.DataTable().ajax.reload();
                        //table.DataTable().draw(false);
                    } else {
                        layer.msg(data.message);
                    }
                });
                return false;
            });

            // 修改
            table.on('click', '.edit-btn', function(event) {
                $(this).prop('disabled', true);
                $(this).parents("tr").siblings("tr").find(".edit-btn").prop('disabled', true);
                $(this).parents('.portlet-sortable').find('.add-adbanner').prop('disabled', true);

                var dataArr = table.DataTable().rows($(this).parents("tr")).data();
                var id = dataArr[0].id;
                var imgUrl = dataArr[0].imgUrl;
                var sorting = dataArr[0].sorting;
                var linkType = dataArr[0].linkType;
                var linkCateId = dataArr[0].linkCateId;
                var linkId = dataArr[0].linkId;

                $(this).parents('.portlet-sortable').find("tbody:last").append(adbannerTemp);
                $("#"+sortableId).find('[name="imgUrl"]').val(imgUrl);
                $("#"+sortableId).find('.exist-img').find('img').attr('src', imgUrl);
                $("#"+sortableId).find('[name="sorting"]').val(sorting);
                $("#"+sortableId).find('[name="linkType"]').val(linkType);
                $("#"+sortableId).find('[name="linkCateId"]').val(linkCateId);
                $("#"+sortableId).find('[name="linkId"]').val(linkId);
                $("#"+sortableId).find('input[name="componentId"]').val(id);
                initUploader();
            });

            // 删除
            table.on('click', '.delete-btn', function(event) {
                var dataArr = table.DataTable().rows($(this).parents("tr")).data();
                var id = dataArr[0].id;
                //var _this = $(this);

                deleteComponent(id, table);
            });
        });

        // 添加轮播图
        $('.add-adbanner').on('click', function(event){
            var count = $(this).parents('.portlet-sortable').find('table tbody').children('tr').length;
            if(count > 10) {
                layer.msg('最多添加10张图片');
                return;
            }
            $(this).prop('disabled', true);
            $(this).parents('.portlet-sortable').find('table .edit-btn').prop('disabled', true);
            $(this).parents('.portlet-sortable').find('table tbody:last').append(adbannerTemp);
            $(this).parents('.portlet-sortable').find("[name='componentId']").val('');
            initUploader();
        });
    };

    // 组合图
    var handle_combinationImg = function () {
        if($('#applet .combinationImg-block').length <= 0){
            return;
        }

        $('#applet .combinationImg-block').each(function(i){
            var top_parent = $(this);
            var sortableId = $(this).attr('id');
            var index = sortableId.substr(8);

            var combinationImg = top_parent.find('input[name="combinationImg"]').val();
            if(combinationImg) {
                combinationImg = JSON.parse(combinationImg);
                //console.log(combinationImg);
                var groupType = combinationImg.groupType;
                top_parent.find('.groupType').val(groupType);

                init_combinationImg(top_parent, index, groupType, combinationImg);
            } else {
                var groupType = top_parent.find('.groupType').val();
                initUploader({'index':index, 'groupType':groupType});
            }
        });


        // 保存组合图
        $('.combinationImg-block').on('click', '.save-btn', function(event) {
            var top_parent = $(this).parents('.portlet-sortable');
            var sortableId = $(this).parents('.portlet-sortable').attr('id');
            var index = sortableId.substr(8);

            var frameId = top_parent.find('input[name="frameId"]').val();
            //var frameName = top_parent.find('input[name="frameName"]').val();
            var backgroudColor = top_parent.find("input[name='backgroudColor']").val();
            var imgUrls = [];
            var linkTypes = [];
            var linkCateIds = [];
            var linkIds = [];
            var displayNames = [];
            top_parent.find('.group-type:visible').find('.upload-image').each(function(){
                if($(this).find('input[name=imgUrl]').length > 0){
                    var imgUrl = $(this).find('input[name=imgUrl]').val();
                    imgUrls.push(imgUrl);
                }else{
                    // layer.msg('请上传图片');
                    // return false;
                }
            });
            if(imgUrls.length < top_parent.find('.group-type:visible').find('.upload-image').length){
                layer.msg('请上传图片');
                return false;
            }

            var is_valid_linkType = true;
            top_parent.find('.group-link:visible').find('select[name=groupLink]').each(function(){
                //var imgLink = $(this).val();
                var linkType = $(this).val();
                if(linkType){
                    linkTypes.push(linkType);
                }

                var linkCateId = $(this).parent().find('input[name=linkCateId]').val();
                var linkId = $(this).parent().find('input[name=linkId]').val();
                if (!isRequireLinkId(linkType)){
                    linkCateId = '';
                    linkId = '';
                } else if (!linkId.trim() && !linkCateId.trim()) {
                    is_valid_linkType = false;
                }
                linkCateIds.push(linkCateId);
                linkIds.push(linkId);
                var displayName = $(this).parent().find('input[name=displayName]').val();
                //if(displayName){
                    displayNames.push(displayName);
                //}
            });
            if(!is_valid_linkType){
                layer.msg('请选择弹框信息');
                return;
            }

            var groupType = top_parent.find('.groupType').val();
            var combinationImg = {
                'groupType': groupType,
                'imgUrls': imgUrls,
                'linkTypes': linkTypes,
                'linkCateIds': linkCateIds,
                'linkIds': linkIds,
                'displayNames': displayNames
            };

            var param = {
                'id': frameId,
                //'frameName': frameName,
                'backgroudColor': backgroudColor,
                'combinationImg': combinationImg,
            };
            $(this).prop('disabled',true);
            saveFrameconf(param);
        });
    };

    // 推荐内容
    var handle_recommend = function () {
        $('#applet .recommend-block').each(function(i){
            var top_parent = $(this);
            var value = top_parent.find('.layoutType').val();

            init_layoutContent(top_parent, top_parent.find('.layoutContent').val());
            init_layoutType(top_parent, value);
        });

        // 保存推荐内容
        $('.recommend-block').on('click', '.save-btn', function(event) {
            var top_parent = $(this).parents('.portlet-sortable');
            var sortableId = $(this).parents('.portlet-sortable').attr('id');
            var index = sortableId.substr(8);

            var frameId = top_parent.find('input[name="frameId"]').val();
            //var frameName = top_parent.find('input[name="frameName"]').val();
            var backgroudColor = top_parent.find("input[name='backgroudColor']").val();
            var fontColor = top_parent.find("input[name='fontColor']").val();
            var layoutType = top_parent.find("select[name='layoutType'] option:selected").val();
            var layoutContent = top_parent.find("select[name='layoutContent'] option:selected").val();
            var showCount = top_parent.find("select[name='showCount'] option:selected").val();
            var showLineCount = top_parent.find("select[name='showLineCount'] option:selected").val();
            if(top_parent.find("input[type='checkbox']").is(':checked')){
                var onlyShowImg = 1;
            }else{
                var onlyShowImg = 2;
            }
            if(layoutType != 2){
                showLineCount = '';
            }
            if(layoutContent == 20){
                layoutType = '';
                showCount = '';
                showLineCount = '';
            }

            var param = {
                'id': frameId,
                //'frameName': frameName,
                'backgroudColor': backgroudColor,
                'fontColor': fontColor,
                'layoutType': layoutType,
                'layoutContent': layoutContent,
                'showCount': showCount,
                'showLineCount': showLineCount,
                'onlyShowImg': onlyShowImg
            };
            $(this).prop('disabled',true);
            saveFrameconf(param);
        });
    };

    // 专题
    var handle_specialtopic = function () {
        $('#applet .specialtopic-block').each(function(i){
            var top_parent = $(this);
            var value = top_parent.find('.layoutType').val();

            init_layoutType(top_parent, value);
        });

        // 保存专题
        $('.specialtopic-block').on('click', '.save-btn', function(event) {
            var top_parent = $(this).parents('.portlet-sortable');
            var sortableId = $(this).parents('.portlet-sortable').attr('id');
            var index = sortableId.substr(8);

            var frameId = top_parent.find('input[name="frameId"]').val();
            //var frameName = top_parent.find('input[name="frameName"]').val();
            var backgroudColor = top_parent.find("input[name='backgroudColor']").val();
            var fontColor = top_parent.find("input[name='fontColor']").val();
            var layoutType = top_parent.find("select[name='layoutType'] option:selected").val();
            var showLineCount = top_parent.find("select[name='showLineCount'] option:selected").val();

            var param = {
                'id': frameId,
                //'frameName': frameName,
                'backgroudColor': backgroudColor,
                'fontColor': fontColor,
                'layoutType': layoutType,
                'showLineCount': showLineCount,
            };
            $(this).prop('disabled',true);
            saveFrameconf(param);
        });
    };

    // 栏目
    var handle_column = function () {
        $('#applet .column-block').each(function(i){
            var top_parent = $(this);
            var value = top_parent.find('.layoutType').val();

            init_layoutType(top_parent, value);
        });

        // 保存栏目
        $('.column-block').on('click', '.save-btn', function(event) {
            var top_parent = $(this).parents('.portlet-sortable');
            var sortableId = $(this).parents('.portlet-sortable').attr('id');
            var index = sortableId.substr(8);

            var frameId = top_parent.find('input[name="frameId"]').val();
            //var frameName = top_parent.find('input[name="frameName"]').val();
            var backgroudColor = top_parent.find("input[name='backgroudColor']").val();
            var layoutType = top_parent.find("select[name='layoutType'] option:selected").val();
            var showLineCount = top_parent.find("select[name='showLineCount'] option:selected").val();

            var param = {
                'id': frameId,
                //'frameName': frameName,
                'backgroudColor': backgroudColor,
                'layoutType': layoutType,
                'showLineCount': showLineCount,
            };
            $(this).prop('disabled',true);
            saveFrameconf(param);
        });
    };

    // 视频
    var handle_vedio = function () {
        // 保存视频
        $('.video-block').on('click', '.save-btn', function(event) {
            var top_parent = $(this).parents('.portlet-sortable');
            var sortableId = $(this).parents('.portlet-sortable').attr('id');
            var index = sortableId.substr(8);

            var frameId = top_parent.find('input[name="frameId"]').val();
            var frameName = top_parent.find('input[name="frameName"]').val();
            var backgroudColor = top_parent.find("input[name='backgroudColor']").val();
            var imgUrl = $('#upload-image-'+index+' [name="imgUrl"]').val();
            var videoUrl = $('#upload-video-'+index+' [name="imgUrl"]').attr('src');

            if (!mdTool.validate(imgUrl, 'require')) {
                layer.msg('请上传视频封面');
                return;
            }
            if (!mdTool.validate(videoUrl, 'require')) {
                layer.msg('请上传视频文件');
                return;
            }
            var param = {
                'frame': {
                    'id': frameId,
                    'name': frameName,
                    'backgroudColor': backgroudColor
                },
                'component': {
                    'frameId': frameId,
                    'displayName': '视频',
                    'sorting': 1,
                    'imgUrl': imgUrl,
                    'videoUrl': videoUrl
                }
            };
            $(this).prop('disabled',true);
            $.ajax({
                url : saveVideo_url,
                type : 'POST',
                dataType : 'json',
                contentType:"application/json; charset=utf-8",
                data : JSON.stringify(param),
            }).done(function(data) {
                if (data.code === '1') {
                    window.location.reload();
                } else {
                    layer.msg(data.message);
                }
            });
            return false;
        });
    };

    // 自适应图片
    var handle_adaptImg = function () {
        if($('#applet .adaptImg-datatable').length <= 0){
            return;
        }

        $('#applet .adaptImg-datatable').each(function(i){
            var top_parent = $(this).parents('.portlet-sortable');
            var sortableId = $(this).parents('.portlet-sortable').attr('id');
            var index = sortableId.substr(8);

            var frameId = top_parent.find('input[name="frameId"]').val();
            var table = $('#adaptImg-datatable'+index);

            table.dataTable({
                "processing": false,
                "ordering": false, // 禁止排序
                destroy: false,
                serverSide: false, // 关闭服务器模式
                "ajax": {
                    url: componentList_url, // 列表查询
                    data: {'frameId':frameId}
                },
                "autoWidth": false,
                "columns": [
                    {
                        "width": "20%",
                        "data": "imgUrl",
                        "render": function(data, type, row, meta) {
                            return '<img class="center-block" src="'+data+'" style="width: 200px;height: 60px;"/>';
                        }
                    },
                    {
                        "width": "20%",
                        "data": "linkType",
                        "render": function(data, type, row, meta) {
                            return getLinkType(data);
                        }
                    },
                    /*{"width": "10%","data": "sorting"},*/
                    {
                        "width": "25%",
                        "data": "null",
                        "defaultContent": defaultOperation
                    }
                ],
                "language": {
                    url: '/public/static/admin/pages/datatable_cn.json'
                },
                "pageLength": 5,
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'table_b relative'<'col-md-5'i><'col-md-7'>p>",
                "fnCreatedRow": function(nRow, aData, iDataIndex){
                    // 将第一张图片放到手机相应预览位置
                    if(iDataIndex == 0) {
                        //
                    }
                },
                "fnInitComplete": function() {}
            });

            // 新增或保存
            table.on('click', '.save-btn', function(event) {
                var imgUrl = $("#"+sortableId).find('[name="imgUrl"]').val();
                var displayName = $("#"+sortableId).find('[name="displayName"]').val();
                var sorting = $("#"+sortableId).find('[name="sorting"]').val();
                var linkType = $("#"+sortableId).find('[name="linkType"]').val();
                var linkCateId = $("#"+sortableId).find('[name="linkCateId"]').val();
                var linkId = $("#"+sortableId).find('[name="linkId"]').val();

                var _id = $("#"+sortableId).find('[name="componentId"]').val();
                var frameId = $("#"+sortableId).find('[name="frameId"]').val();// 模块id

                if (!mdTool.validate(imgUrl, 'require')) {
                    layer.msg('请上传图片');
                    return;
                }
                if (!mdTool.validate(linkType, 'require')) {
                    layer.msg('请选择链接类型');
                    return;
                }
                if (!isRequireLinkId(linkType)){
                    linkCateId = '';
                    linkId = '';
                } else if (!linkId.trim() && !linkCateId.trim()) {
                    layer.msg('请选择弹框信息');
                    return;
                }
                /*if (!mdTool.validate(sorting, 'num')) {
                    layer.msg('请输入正确的排序');
                    return;
                }*/

                var param = {
                    'id': _id,
                    'frameId': frameId,
                    'imgUrl': imgUrl,
                    'sorting': sorting,
                    'linkType': linkType,
                    'linkCateId': linkCateId,
                    'linkId': linkId,
                    'displayName': displayName
                };
                var _type = _id == null||_id == '' ? "put" : "post";

                $.ajax({
                    url : saveComponent_url,
                    type : _type,
                    dataType : 'json',
                    contentType:"application/json; charset=utf-8",
                    data : JSON.stringify(param),
                }).done(function(data) {
                    $("#"+sortableId).find('.add-adaptImg').prop('disabled', false);
                    if (data.code === '1') {
                        table.DataTable().ajax.reload();
                        //table.DataTable().draw(false);
                    } else {
                        layer.msg(data.message);
                    }
                });
                return false;
            });

            // 修改
            table.on('click', '.edit-btn', function(event) {
                $(this).prop('disabled', true);
                $(this).parents("tr").siblings("tr").find(".edit-btn").prop('disabled', true);
                $(this).parents('.portlet-sortable').find('.add-adaptImg').prop('disabled', true);

                var dataArr = table.DataTable().rows($(this).parents("tr")).data();
                var id = dataArr[0].id;
                var imgUrl = dataArr[0].imgUrl;
                var sorting = dataArr[0].sorting;
                var linkType = dataArr[0].linkType;
                var linkCateId = dataArr[0].linkCateId;
                var linkId = dataArr[0].linkId;

                $(this).parents('.portlet-sortable').find("tbody:last").append(adaptImgTemp);
                $("#"+sortableId).find('[name="imgUrl"]').val(imgUrl);
                $("#"+sortableId).find('.exist-img').find('img').attr('src', imgUrl);
                $("#"+sortableId).find('[name="sorting"]').val(sorting);
                $("#"+sortableId).find('[name="linkType"]').val(linkType);
                $("#"+sortableId).find('[name="linkCateId"]').val(linkCateId);
                $("#"+sortableId).find('[name="linkId"]').val(linkId);
                $("#"+sortableId).find('input[name="componentId"]').val(id);
                initUploader();
            });

            // 删除
            table.on('click', '.delete-btn', function(event) {
                var dataArr = table.DataTable().rows($(this).parents("tr")).data();
                var id = dataArr[0].id;
                //var _this = $(this);

                deleteComponent(id, table);
            });
        });

        // 添加自适应图片
        $('.add-adaptImg').on('click', function(event){
            var count = $(this).parents('.portlet-sortable').find('table tbody').children('tr[role=row]').length;
            if(count >= 1) {
                layer.msg('最多添加1张图片');
                return;
            }
            $(this).prop('disabled', true);
            $(this).parents('.portlet-sortable').find('table .edit-btn').prop('disabled', true);
            $(this).parents('.portlet-sortable').find('table tbody:last').append(adaptImgTemp);
            $(this).parents('.portlet-sortable').find("[name='componentId']").val('');
            initUploader();
        });
    };

    // 按钮导航
    var handle_buttonNav = function () {
        if($('#applet .buttonNav-datatable').length <= 0){
            return;
        }

        $('#applet .buttonNav-datatable').each(function(i){
            var top_parent = $(this).parents('.portlet-sortable');
            var sortableId = $(this).parents('.portlet-sortable').attr('id');
            var index = sortableId.substr(8);

            var frameId = top_parent.find('input[name="frameId"]').val();
            var table = $('#buttonNav-datatable'+index);

            table.dataTable({
                "processing": false,
                "ordering": false, // 禁止排序
                destroy: false,
                serverSide: false, // 关闭服务器模式
                "ajax": {
                    url: componentList_url, // 列表查询
                    data: {'frameId':frameId}
                },
                "autoWidth": false,
                "columns": [
                    {
                        "width": "20%",
                        "data": "imgUrl",
                        "render": function(data, type, row, meta) {
                            return '<img class="center-block" src="'+data+'" style="width: 200px;height: 60px;"/>';
                        }
                    },
                    {"width": "20%","data": "displayName"},
                    {
                        "width": "20%",
                        "data": "linkType",
                        "render": function(data, type, row, meta) {
                            return getLinkType(data);
                        }
                    },
                    {"width": "10%","data": "sorting"},
                    {
                        "width": "25%",
                        "data": "null",
                        "defaultContent": defaultOperation
                    }
                ],
                "language": {
                    url: '/public/static/admin/pages/datatable_cn.json'
                },
                "pageLength": 5,
                "order": [
                    [3, "asc"]
                ],
                "columnDefs": [{
                    "orderable": false,
                    "targets": [0, 4]
                }],
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'table_b relative'<'col-md-5'i><'col-md-7'>p>",
                "fnCreatedRow": function(nRow, aData, iDataIndex){
                    // 将第一张图片放到手机相应预览位置
                    if(iDataIndex == 0) {
                        //
                    }
                },
                "fnInitComplete": function() {}
            });

            // 新增或保存
            table.on('click', '.save-btn', function(event) {
                var imgUrl = $("#"+sortableId).find('[name="imgUrl"]').val();
                var displayName = $("#"+sortableId).find('[name="displayName"]').val();
                var sorting = $("#"+sortableId).find('[name="sorting"]').val();
                var linkType = $("#"+sortableId).find('[name="linkType"]').val();
                var linkCateId = $("#"+sortableId).find('[name="linkCateId"]').val();
                var linkId = $("#"+sortableId).find('[name="linkId"]').val();

                var _id = $("#"+sortableId).find('[name="componentId"]').val();
                var frameId = $("#"+sortableId).find('[name="frameId"]').val();// 模块id

                if (!mdTool.validate(imgUrl, 'require')) {
                    layer.msg('请上传图片');
                    return;
                }
                if (!mdTool.validate(displayName, 'require')) {
                    layer.msg('请输入按钮名称');
                    return;
                }
                if (!mdTool.validate(linkType, 'require')) {
                    layer.msg('请选择链接类型');
                    return;
                }
                if (!isRequireLinkId(linkType)){
                    linkCateId = '';
                    linkId = '';
                } else if (!linkId.trim() && !linkCateId.trim()) {
                    layer.msg('请选择弹框信息');
                    return;
                }
                if (!mdTool.validate(sorting, 'num')) {
                    layer.msg('请输入正确的排序');
                    return;
                }

                var param = {
                    'id': _id,
                    'frameId': frameId,
                    'imgUrl': imgUrl,
                    'sorting': sorting,
                    'linkType': linkType,
                    'linkCateId': linkCateId,
                    'linkId': linkId,
                    'displayName': displayName
                };
                var _type = _id == null||_id == '' ? "put" : "post";

                $.ajax({
                    url : saveComponent_url,
                    type : _type,
                    dataType : 'json',
                    contentType:"application/json; charset=utf-8",
                    data : JSON.stringify(param),
                }).done(function(data) {
                    $("#"+sortableId).find('.add-buttonNav').prop('disabled', false);
                    if (data.code === '1') {
                        table.DataTable().ajax.reload();
                        //table.DataTable().draw(false);
                    } else {
                        layer.msg(data.message);
                    }
                });
                return false;
            });

            // 修改
            table.on('click', '.edit-btn', function(event) {
                $(this).prop('disabled', true);
                $(this).parents("tr").siblings("tr").find(".edit-btn").prop('disabled', true);
                $(this).parents('.portlet-sortable').find('.add-buttonNav').prop('disabled', true);

                var dataArr = table.DataTable().rows($(this).parents("tr")).data();
                var id = dataArr[0].id;
                var imgUrl = dataArr[0].imgUrl;
                var displayName = dataArr[0].displayName;
                var sorting = dataArr[0].sorting;
                var linkType = dataArr[0].linkType;
                var linkCateId = dataArr[0].linkCateId;
                var linkId = dataArr[0].linkId;

                $(this).parents('.portlet-sortable').find("tbody:last").append(buttonNavTemp);
                $("#"+sortableId).find('[name="imgUrl"]').val(imgUrl);
                $("#"+sortableId).find('.exist-img').find('img').attr('src', imgUrl);
                $("#"+sortableId).find('[name="displayName"]').val(displayName);
                $("#"+sortableId).find('[name="sorting"]').val(sorting);
                $("#"+sortableId).find('[name="linkType"]').val(linkType);
                $("#"+sortableId).find('[name="linkCateId"]').val(linkCateId);
                $("#"+sortableId).find('[name="linkId"]').val(linkId);
                $("#"+sortableId).find('input[name="componentId"]').val(id);
                initUploader();
            });

            // 删除
            table.on('click', '.delete-btn', function(event) {
                var dataArr = table.DataTable().rows($(this).parents("tr")).data();
                var id = dataArr[0].id;
                //var _this = $(this);

                deleteComponent(id, table);
            });
        });

        // 添加按钮导航
        $('.add-buttonNav').on('click', function(event){
            var count = $(this).parents('.portlet-sortable').find('table tbody').children('tr').length;
            if(count > 12) {
                layer.msg('最多添加12张图片');
                return;
            }
            $(this).prop('disabled', true);
            $(this).parents('.portlet-sortable').find('table .edit-btn').prop('disabled', true);
            $(this).parents('.portlet-sortable').find('table tbody:last').append(buttonNavTemp);
            $(this).parents('.portlet-sortable').find("[name='componentId']").val('');
            initUploader();
        });

        // 保存按钮导航
        $('.buttonNav-block').on('click', '.save-block-btn', function(event) {
            var top_parent = $(this).parents('.portlet-sortable');
            var sortableId = $(this).parents('.portlet-sortable').attr('id');
            var index = sortableId.substr(8);

            var frameId = top_parent.find('input[name="frameId"]').val();
            //var frameName = top_parent.find('input[name="frameName"]').val();
            var backgroudColor = top_parent.find("input[name='backgroudColor']").val();
            var fontColor = top_parent.find("input[name='fontColor']").val();

            var param = {
                'id': frameId,
                //'frameName': frameName,
                'backgroudColor': backgroudColor,
                'fontColor': fontColor,
            };
            $(this).prop('disabled',true);
            saveFrameconf(param);
        });
    };

    // 分割线
    var handle_dividingline = function () {
        //
    };

    // 保存模块数据
    var saveFrameconf = function (param) {
        $.ajax({
            url : saveFrameconf_url,
            type : 'PUT',
            dataType : 'json',
            contentType:"application/json; charset=utf-8",
            data : JSON.stringify(param),
        }).done(function(data) {
            if (data.code === '1') {
                window.location.reload();
            } else {
                layer.msg(data.message)
            }
        });
    };

    // 模块内部列表（小程序组件内容）的删除
    var deleteComponent = function (_id, table) {
        var param = {'id': _id};

        layer.confirm(
            '确定要删除吗？', // 内容
            {
                // icon: 7,
                title: '删除',// 标题
                btn: ['确定', '取消']  // 按钮
            },
            function(index){
                $.ajax({
                    url : delComponent_url,
                    type : 'delete',
                    dataType : 'json',
                    contentType:"application/json; charset=utf-8",
                    data : JSON.stringify(param),
                    async: false
                }).done(function(data) {
                    if (data.code === '1') {
                        layer.msg('删除成功');
                        table.DataTable().ajax.reload();
                        //table.DataTable().draw(false);
                    } else {
                        layer.msg(data.message);
                    }
                });
                layer.close(index);
            }
        );
    };

    // 初始化组合图
    var init_combinationImg = function (top_parent, index, groupType, combinationImg) {
        // 组合图
        top_parent.find('.groupType1, .groupType2, .groupType3, .groupType4, .groupType5, .groupType6').hide();
        top_parent.find('.groupType'+groupType).show();

        initUploader({'index':index, 'groupType':groupType});

        // 链接
        top_parent.find('.groupLink1, .groupLink2, .groupLink3, .groupLink4, .groupLink5').hide();
        switch (groupType) {
            case '1':
                top_parent.find('.groupLink1, .groupLink2').show();
                break;
            case '2':
                top_parent.find('.groupLink1, .groupLink2, .groupLink3').show();
                break;
            case '3':
                top_parent.find('.groupLink1, .groupLink2, .groupLink3').show();
                break;
            case '4':
                top_parent.find('.groupLink1, .groupLink2, .groupLink3, .groupLink4').show();
                break;
            case '5':
                top_parent.find('.groupLink1, .groupLink2, .groupLink3, .groupLink4, .groupLink5').show();
                break;
            case '6':
                top_parent.find('.groupLink1, .groupLink2, .groupLink3, .groupLink4, .groupLink5').show();
                break;
            default: break;
        }

        console.log(combinationImg);
        if(combinationImg){
            var imgUrls = combinationImg.imgUrls;
            var linkTypes = combinationImg.linkTypes;
            var linkCateIds = combinationImg.linkCateIds;
            var linkIds = combinationImg.linkIds;
            var displayNames = combinationImg.displayNames;

            top_parent.find('.upload-image:visible').each(function(i){
                var html = '';
                html += '<div class="exist-img">';
                html += '<input type="hidden" class="form-control" name="imgUrl" value="'+imgUrls[i]+'">';
                html += '<img src="'+imgUrls[i]+'" alt="图片上传" />';
                html += '</div>';

                $(this).children().find('.uploader-div').hide();
                $(this).children().append(html);
            });
            top_parent.find('.group-link:visible').each(function(i){
                if(linkTypes){
                    $(this).find('select[name=groupLink]').val(linkTypes[i]);
                }
                if(linkCateIds){
                    $(this).find('input[name=linkCateId]').val(linkCateIds[i]);
                }
                if(linkIds){
                    $(this).find('input[name=linkId]').val(linkIds[i]);
                }
                if(displayNames){
                    $(this).find('input[name=displayName]').val(displayNames[i]);
                }
            });
        }
    };

    // 布局
    var init_layoutType = function (top_parent, value) {
        if(value == 2){
            top_parent.find('.show-line').show();
        }else{
            top_parent.find('.show-line').hide();
        }
    };

    // 显示内容
    var init_layoutContent = function (top_parent, value) {
        if(value == 20){
            // 动态没有布局
            top_parent.find('.layout-type').hide();
            top_parent.find('.show-line').hide();
            top_parent.find('.show-count').hide();
        }else{
            top_parent.find('.layout-type').show();
            top_parent.find('.show-line').show();
            top_parent.find('.show-count').show();
        }
    };


    //++ 七牛上传初始化 Begin ++//
    var token_url = $('.token_url').val();
    var record_url = $('.record_url').val();
    var max_file_size = '1MB';
    var extensions = 'jpg,jpeg,gif,png';
    var multi = false;
    var initUploader = function (param) {
        $.ajax({
            url: token_url,
            type: 'POST',
            data: {},
            cache: false,
            contentType: false,    //不可缺
            processData: false,    //不可缺
            dataType : 'json',
            success: function (data) {
                var url = "";
                var qiniupercent = "";

                if(param) {
                    // 组合图
                    var index = param.index;
                    switch (param.groupType) {
                        case '1':
                            //var pickfiles = ['upload-btn1-1-'+index,'upload-btn1-2-'+index];
                            //window.load_upload_image1 = 'upload-image1-1-'+index;
                            //if(load_upload_image1){
                            if($.inArray('upload-image1-1-'+index, load_upload_image1_arr) < 0){
                                uploaderImgReady(data.uptoken, url, qiniupercent, 'upload-image1-1-'+index, 'upload-btn1-1-'+index, max_file_size, extensions, multi);
                                uploaderImgReady(data.uptoken, url, qiniupercent, 'upload-image1-2-'+index, 'upload-btn1-2-'+index, max_file_size, extensions, multi);

                                load_upload_image1_arr.push('upload-image1-1-'+index);
                            }
                            //load_upload_image1 = false;
                            break;
                        case '2':
                            //var pickfiles = ['upload-btn2-1-'+index,'upload-btn2-2-'+index,'upload-btn2-3-'+index];
                            if($.inArray('upload-image2-1-'+index, load_upload_image2_arr) < 0){
                                uploaderImgReady(data.uptoken, url, qiniupercent, 'upload-image2-1-'+index, 'upload-btn2-1-'+index, max_file_size, extensions, multi);
                                uploaderImgReady(data.uptoken, url, qiniupercent, 'upload-image2-2-'+index, 'upload-btn2-2-'+index, max_file_size, extensions, multi);
                                uploaderImgReady(data.uptoken, url, qiniupercent, 'upload-image2-3-'+index, 'upload-btn2-3-'+index, max_file_size, extensions, multi);

                                load_upload_image2_arr.push('upload-image2-1-'+index);
                            }
                            //load_upload_image2 = false;
                            break;
                        case '3':
                            //var pickfiles = ['upload-btn3-1-'+index,'upload-btn3-2-'+index,'upload-btn3-3-'+index];
                            if($.inArray('upload-image3-1-'+index, load_upload_image3_arr) < 0){
                                uploaderImgReady(data.uptoken, url, qiniupercent, 'upload-image3-1-'+index, 'upload-btn3-1-'+index, max_file_size, extensions, multi);
                                uploaderImgReady(data.uptoken, url, qiniupercent, 'upload-image3-2-'+index, 'upload-btn3-2-'+index, max_file_size, extensions, multi);
                                uploaderImgReady(data.uptoken, url, qiniupercent, 'upload-image3-3-'+index, 'upload-btn3-3-'+index, max_file_size, extensions, multi);

                                load_upload_image3_arr.push('upload-image3-1-'+index);
                            }
                            //load_upload_image3 = false;
                            break;
                        case '4':
                            //var pickfiles = ['upload-btn4-1-'+index,'upload-btn4-2-'+index,'upload-btn4-3-'+index,'upload-btn4-4-'+index];
                            if($.inArray('upload-image4-1-'+index, load_upload_image4_arr) < 0){
                                uploaderImgReady(data.uptoken, url, qiniupercent, 'upload-image4-1-'+index, 'upload-btn4-1-'+index, max_file_size, extensions, multi);
                                uploaderImgReady(data.uptoken, url, qiniupercent, 'upload-image4-2-'+index, 'upload-btn4-2-'+index, max_file_size, extensions, multi);
                                uploaderImgReady(data.uptoken, url, qiniupercent, 'upload-image4-3-'+index, 'upload-btn4-3-'+index, max_file_size, extensions, multi);
                                uploaderImgReady(data.uptoken, url, qiniupercent, 'upload-image4-4-'+index, 'upload-btn4-4-'+index, max_file_size, extensions, multi);

                                load_upload_image4_arr.push('upload-image4-1-'+index);
                            }
                            //load_upload_image4 = false;
                            break;
                        case '5':
                            //var pickfiles = ['upload-btn5-1-'+index,'upload-btn5-2-'+index,'upload-btn5-3-'+index,'upload-btn5-4-'+index,'upload-btn5-5-'+index];
                            if($.inArray('upload-image5-1-'+index, load_upload_image5_arr) < 0){
                                uploaderImgReady(data.uptoken, url, qiniupercent, 'upload-image5-1-'+index, 'upload-btn5-1-'+index, max_file_size, extensions, multi);
                                uploaderImgReady(data.uptoken, url, qiniupercent, 'upload-image5-2-'+index, 'upload-btn5-2-'+index, max_file_size, extensions, multi);
                                uploaderImgReady(data.uptoken, url, qiniupercent, 'upload-image5-3-'+index, 'upload-btn5-3-'+index, max_file_size, extensions, multi);
                                uploaderImgReady(data.uptoken, url, qiniupercent, 'upload-image5-4-'+index, 'upload-btn5-4-'+index, max_file_size, extensions, multi);
                                uploaderImgReady(data.uptoken, url, qiniupercent, 'upload-image5-5-'+index, 'upload-btn5-5-'+index, max_file_size, extensions, multi);

                                load_upload_image5_arr.push('upload-image5-1-'+index);
                            }
                            //load_upload_image5 = false;
                            break;
                        case '6':
                            //var pickfiles = ['upload-btn6-1-'+index,'upload-btn6-2-'+index,'upload-btn6-3-'+index,'upload-btn6-4-'+index,'upload-btn6-5-'+index];
                            if($.inArray('upload-image6-1-'+index, load_upload_image6_arr) < 0){
                                uploaderImgReady(data.uptoken, url, qiniupercent, 'upload-image6-1-'+index, 'upload-btn6-1-'+index, max_file_size, extensions, multi);
                                uploaderImgReady(data.uptoken, url, qiniupercent, 'upload-image6-2-'+index, 'upload-btn6-2-'+index, max_file_size, extensions, multi);
                                uploaderImgReady(data.uptoken, url, qiniupercent, 'upload-image6-3-'+index, 'upload-btn6-3-'+index, max_file_size, extensions, multi);
                                uploaderImgReady(data.uptoken, url, qiniupercent, 'upload-image6-4-'+index, 'upload-btn6-4-'+index, max_file_size, extensions, multi);
                                uploaderImgReady(data.uptoken, url, qiniupercent, 'upload-image6-5-'+index, 'upload-btn6-5-'+index, max_file_size, extensions, multi);

                                load_upload_image6_arr.push('upload-image6-1-'+index);
                            }
                            //load_upload_image6 = false;
                            break;
                        default: break;
                    }
                    //uploaderImgReady(data.uptoken, url, qiniupercent, 'upload-image-'+index, pickfiles, max_file_size, extensions, multi);
                } else {
                    // 轮播图
                    if($('#upload-image').length > 0){
                        uploaderImgReady(data.uptoken, url, qiniupercent, 'upload-image', 'upload-btn', max_file_size, extensions, multi);
                    }

                    // 视频
                    if(load_upload_video){
                        if($('.video-block').length >= 1) {
                            $('.video-block').each(function(i){
                                var sortableId = $(this).attr('id');
                                var index = sortableId.substr(8);
                                uploaderImgReady(data.uptoken, url, qiniupercent, 'upload-image-'+index, 'upload-btn-'+index, max_file_size, extensions, multi);
                                uploaderVideoReady(data.uptoken, url, qiniupercent, 'upload-video-'+index, 'upload-video-btn-'+index, '100M', 'mp4', multi);
                            });
                        }
                    }
                    load_upload_video = false;
                }
            }
        });
    };
    var uploaderImgReady = function (token, url, qiniupercent, uploader, pickfiles, max_file_size, extensions, multi) {
        var uploaderForUditor = Qiniu.uploader({
            runtimes: 'html5,flash,html4',
            browse_button: pickfiles,     //上传按钮的ID
            // container: uploader,      //上传按钮的上级元素ID
            // drop_element: uploader,
            max_file_size: max_file_size,         //最大文件限制
            flash_swf_url: '@{/assets/global/qiniu/Moxie.swf}',
            dragdrop: false,
            chunk_size: '4mb',              //分块大小
            //uptoken_url: '',              //Ajax请求upToken的Url，**强烈建议设置**（服务端提供）
            uptoken: token,                 //若未指定uptoken_url,则必须指定 uptoken ,uptoken由其他程序生成
            // save_key: true,              // 默认 false。若在服务端生成uptoken的上传策略中指定了 `sava_key`，则开启，SDK在前端将不对key进行任何处理
            domain: qiniuConfig.returnUrl(),   //自己的七牛云存储空间域名
            multi_selection: multi,         //是否允许同时选择多文件
            filters: {
                mime_types: [               //文件类型过滤，这里限制为图片类型
                    {title: "Image files", extensions: extensions}
                ]
            },
            auto_start: true,
            unique_names :true,             //自动生成文件名,如果值为false则保留原文件名上传
            init: {
                'FilesAdded': function (up, files) {
                    plupload.each(files, function(file) {
                        // 文件添加进队列后，处理相关的事情
                    });
                },
                'BeforeUpload': function (up, file) {
                    // 每个文件上传前，处理相关的事情
                    layer.load(2, {shade: [0.8,'#000000']}); // 打开loading
                },
                'UploadProgress': function (up, file) {
                    //文件上传时，处理相关的事情

                    //上传进度 class="layui-btn" type="button"

                    //console.log(file.percent + "%");
                },
                'UploadComplete': function () {
                    //do something
                },
                'FileUploaded': function (up, file, info) {
                    //每个文件上传成功后,处理相关的事情,并记录到数据库
                    //其中 info 是文件上传成功后，服务端返回的json，形式如
                    //{
                    //  "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
                    //  "key": "gogopher.jpg"
                    //}
                    var domain = up.getOption('domain');
                    var res = eval('(' + info.response + ')');
                    var sourceLink = domain + res.key;//获取上传文件的链接地址
                    //console.log(sourceLink);
                    $.ajax({
                        url: record_url,
                        type: 'POST',
                        data: {
                            'imgUrl': sourceLink
                        },
                        cache: false,
                        dataType: 'json',
                        success: function (data) {
                            //console.log(data);
                            layer.closeAll('loading'); // 关闭loading
                            if (data.code === '1') {
                                // 删除原图
                                var img_id = $('#' + pickfiles).find('input[name=imgId]').val();
                                var img_url = $('#' + pickfiles).find('img').attr('src');
                                delOriginalImg(img_id, img_url);

                                if($('#' + pickfiles).find('.exist-img').length > 0) {
                                    $('#' + pickfiles).find('img').attr('src', sourceLink);
                                    $('#' + pickfiles).find('input[name=imgUrl]').val(sourceLink);
                                    $('#' + pickfiles).find('input[name=imgId]').val(data.image_id);
                                } else {
                                    var html = '';
                                    html += '<div class="exist-img">';
                                    html += '<input type="hidden" class="form-control" name="imgUrl" value="'+sourceLink+'">';
                                    html += '<img src="'+sourceLink+'" alt="图片上传" />';
                                    html += '</div>';

                                    $('#' + pickfiles).find('.uploader-div').hide();
                                    $('#' + pickfiles).append(html);
                                    $('#' + pickfiles).append('<input type="hidden" name="imgId" value="'+data.image_id+'">');
                                }
                            }
                        }
                    });

                },
                'Error': function (up, err, errTip) {
                    layer.closeAll('loading'); // 关闭loading
                    alert(errTip);
                },
            }
        });
    };
    var uploaderVideoReady = function (token, url, qiniupercent, uploader, pickfiles, max_file_size, extensions, multi) {
        var uploaderForUditor = Qiniu.uploader({
            runtimes: 'html5,flash,html4',
            browse_button: pickfiles,     //上传按钮的ID
            // container: uploader,      //上传按钮的上级元素ID
            // drop_element: uploader,
            max_file_size: max_file_size,         //最大文件限制
            flash_swf_url: '@{/assets/global/qiniu/Moxie.swf}',
            dragdrop: false,
            chunk_size: '4mb',              //分块大小
            //uptoken_url: '',              //Ajax请求upToken的Url，**强烈建议设置**（服务端提供）
            uptoken: token,                 //若未指定uptoken_url,则必须指定 uptoken ,uptoken由其他程序生成
            // save_key: true,              // 默认 false。若在服务端生成uptoken的上传策略中指定了 `sava_key`，则开启，SDK在前端将不对key进行任何处理
            domain: qiniuConfig.returnUrl(),   //自己的七牛云存储空间域名
            multi_selection: multi,         //是否允许同时选择多文件
            filters: {
                mime_types: [               //文件类型过滤，这里限制为图片类型
                    {title: "Image files", extensions: extensions}
                ]
            },
            auto_start: true,
            unique_names :true,             //自动生成文件名,如果值为false则保留原文件名上传
            init: {
                'FilesAdded': function (up, files) {
                    plupload.each(files, function(file) {
                        // 文件添加进队列后，处理相关的事情
                    });
                },
                'BeforeUpload': function (up, file) {
                    // 每个文件上传前，处理相关的事情
                    layer.load(2, {shade: [0.8,'#000000']}); // 打开loading
                },
                'UploadProgress': function (up, file) {
                    //文件上传时，处理相关的事情

                    //上传进度 class="layui-btn" type="button"

                    //console.log(file.percent + "%");
                },
                'UploadComplete': function () {
                    //do something
                },
                'FileUploaded': function (up, file, info) {
                    //每个文件上传成功后,处理相关的事情,并记录到数据库
                    //其中 info 是文件上传成功后，服务端返回的json，形式如
                    //{
                    //  "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
                    //  "key": "gogopher.jpg"
                    //}
                    var domain = up.getOption('domain');
                    var res = eval('(' + info.response + ')');
                    var sourceLink = domain + res.key;//获取上传文件的链接地址
                    //console.log(sourceLink);
                    $.ajax({
                        url: record_url,
                        type: 'POST',
                        data: {
                            'imgUrl': sourceLink
                        },
                        cache: false,
                        dataType: 'json',
                        success: function (data) {
                            layer.closeAll('loading'); // 关闭loading
                            if (data.code === '1') {
                                // 删除原图
                                var img_id = $('#' + pickfiles).find('input[name=imgId]').val();
                                var img_url = $('#' + pickfiles).find('video').attr('src');
                                delOriginalImg(img_id, img_url);

                                if($('#' + pickfiles).find('video').length > 0){
                                    $('#' + pickfiles).find('video').attr('src', sourceLink);
                                }else{
                                    var video_html = '<video class="img-responsive" name="imgUrl" src="'+sourceLink+'" />  <source name="imgUrl" class="img-responsive" src="'+sourceLink+'" type="video/mp4" /> </video>';
                                    $('#' + pickfiles).find('.uploader-div').empty().html(video_html);
                                }

                                $('#' + pickfiles).find('input[name=imgUrl]').val(sourceLink);
                                if($('#' + pickfiles).find('input[name=imgId]').length > 0){
                                    $('#' + pickfiles).find('input[name=imgId]').val(data.image_id);
                                }else{
                                    $('#' + pickfiles).append('<input type="hidden" name="imgId" value="'+data.image_id+'">');
                                }
                            }
                        }
                    });

                },
                'Error': function (up, err, errTip) {
                    layer.closeAll('loading'); // 关闭loading
                    alert(errTip);
                },
            }
        });
    };
    // 删除原图
    var delOriginalImg = function (img_id, img_url) {
        var delimage_url = $('.delimage_url').val();

        $.ajax({
            url: delimage_url,
            type: 'POST',
            data: {
                'imgUrl' : img_url,
                'id' : img_id
            },
            cache: false,
            dataType : 'json',
            success: function (data) {
                //
            }
        });
    };
    //++ 七牛上传初始化 End ++//


    return {
        init: function() {
            _init();
            initSortable();
            initMiniColors();
            initUploader('');

            this.onEvent();
        },

        onEvent : function(){


            // 折叠模块
            $('.collapse-btn').on('click', function(){
                if($(this).find('.fa-chevron-down').length > 0){
                    $(this).find('i').removeClass('fa-chevron-down').addClass('fa-chevron-up');
                    $(this).parents('.portlet-sortable').find('.portlet-body').hide();
                }else{
                    $(this).find('i').removeClass('fa-chevron-up').addClass('fa-chevron-down');
                    $(this).parents('.portlet-sortable').find('.portlet-body').show();
                }
            });

            // 删除模块
            $("#applet").on('click', '.del-module',function(){
                var frameId = $(this).parents('.portlet-sortable').find('input[name=frameId]').val();
                if(!frameId){
                    return false;
                }
                var _this = $(this);
                var param = {'frameId':frameId};
                layer.confirm(
                    '确定要删除吗？', // 内容
                    {
                        // icon: 7,
                        title: '删除',// 标题
                        btn: ['确定', '取消']  // 按钮
                    },
                    function(index){
                        $.ajax({
                            url : delFrameconf_url,
                            type : 'delete',
                            dataType : 'json',
                            contentType:"application/json; charset=utf-8",
                            data : JSON.stringify(param),
                            async: false
                        }).done(function(data) {
                            if (data.code === '1') {
                                layer.msg('删除成功');
                                _this.parents('.portlet-sortable').remove();
                                //window.location.reload();
                            } else {
                                layer.msg(data.message);
                            }
                        });
                        layer.close(index);
                    }
                );
            });

            // 模块内部 取消按钮 （通用）
            $("#applet").on('click', '.cancle-btn',function(){
                $(this).parents('table').find('.edit-btn').prop('disabled', false);
                $(this).parents('.portlet-sortable').find('.add-block-btn').prop('disabled', false);
                $(this).parents('tr').remove();
                return false;
            });

            // 添加轮播图
            $('.add-adbanner-block').on('click', function(){
                var param = {
                    'name': '轮播图',
                    'typeId': 1,
                    'sorting': 1
                };
                saveFrameconf(param);
            });
            // 添加组合图
            $('.add-combinationImg-block').on('click', function(){
                var param = {
                    'name': '组合图',
                    'typeId': 2,
                    'sorting': 1
                };
                saveFrameconf(param);
            });
            // 添加推荐内容
            $('.add-recommend-block').on('click', function(){
                var param = {
                    'name': '内容版块',
                    'typeId': 3,
                    'sorting': 1
                };
                saveFrameconf(param);
            });
            // 添加专题
            /*$('.add-specialtopic-block').on('click', function(){
                var param = {
                    'name': '专题',
                    'typeId': 8,
                    'sorting': 1
                };
                saveFrameconf(param);
            });*/
            // 添加栏目
            /*$('.add-column-block').on('click', function(){
                var param = {
                    'name': '栏目',
                    'typeId': 9,
                    'sorting': 1
                };
                saveFrameconf(param);
            });*/
            // 添加视频
            $('.add-video-block').on('click', function(){
                if($('#applet').find('.video-block').length > 0){
                    layer.msg('视频只能添加一个！');
                    return false;
                }

                var param = {
                    'name': '视频',
                    'typeId': 4,
                    'sorting': 1
                };
                saveFrameconf(param);
            });
            // 添加自适应图片
            $('.add-adaptImg-block').on('click', function(){
                var param = {
                    'name': '自适应图片',
                    'typeId': 6,
                    'sorting': 1
                };
                saveFrameconf(param);
            });
            // 添加按钮导航
            $('.add-buttonNav-block').on('click', function(){
                var param = {
                    'name': '按钮导航',
                    'typeId': 7,
                    'sorting': 1
                };
                saveFrameconf(param);
            });
            // 添加分割线
            $('.add-dividingline-block').on('click', function(){
                var param = {
                    'name': '分割线',
                    'typeId': 5,
                    'sorting': 1
                };
                saveFrameconf(param);
            });


            // 切换组合方式
            $('.groupType').on('change', function(){
                var top_parent = $(this).parents('.portlet-sortable');
                var value = $(this).val();

                var sortableId = top_parent.attr('id');
                var index = sortableId.substr(8);

                init_combinationImg(top_parent, index, value);
            });

            // 切换布局
            $('.layoutType').on('change', function(){
                var top_parent = $(this).parents('.portlet-sortable');
                var value = $(this).val();

                init_layoutType(top_parent, value);
            });

            // 选择显示内容
            $('.layoutContent').on('change', function(){
                var top_parent = $(this).parents('.portlet-sortable');
                var value = $(this).val();

                init_layoutContent(top_parent, value);
            });


            // 更新排序
            /*$('#applet').nestable().on('change', function(){
                var r = $('.dd').nestable('serialize');
                console.log(r);
                console.log(JSON.stringify(r));
            });*/
        }
    };

}();


$(function() {
    Customhome.init();

});

// 根据链接ID得到链接名
function getLinkType($data) {
    switch ($data) {
        case '0':
            return '无链接';
            break;
        case '1':
            return '头条';
            break;
        case '2':
            return '村子';
            break;
        /*case '3':
            return '村民';
            break;
        case '4':
            return '公告栏';
            break;*/
        case '5':
            return '乡镇机关';
            break;
        case '6':
            return '农事知识';
            break;
        /*case '7':
            return '本地特色';
            break;*/
        case '8':
            return '特色专题';
            break;
        case '9':
            return '党务公示';
            break;
        case '10':
            return '党建要闻';
            break;
        case '11':
            return '党课学习';
            break;
        case '12':
            return '考试测评';
            break;
        /*case '13':
            return '会议';
            break;*/
        case '14':
            return '投票调研';
            break;
        case '15':
            return '组织活动';
            break;
        case '16':
            return '扶贫动态';
            break;
        case '17':
            return '扶贫项目';
            break;
        case '18':
            return '扶贫政策';
            break;
        case '19':
            return '一村一品';
            break;
        case '20':
            return '百事通';
            break;
        case '21':
            return '便民服务';
            break;
        case '22':
            return '智慧党建';
            break;
        case '23':
            return '精准扶贫';
            break;
        case '24':
            return '产地直供';
            break;
        case '25':
            return '知识分类';
            break;

        case '41':
            return '头条详情';
            break;
        case '42':
            return '村子详情';
            break;
        case '43':
            return '知识列表';
            break;
        case '44':
            return '知识详情';
            break;
        case '45':
            return '特色专题列表';
            break;
        case '46':
            return '特色专题详情';
            break;
        case '47':
            return '党务公示详情';
            break;
        case '48':
            return '党建要闻分类';
            break;
        case '49':
            return '党建要闻详情';
            break;
        case '50':
            return '党课分类';
            break;
        case '51':
            return '产品分类';
            break;
        case '52':
            return '产品详情';
            break;
        default: break;
    }
}

// 判断链接ID是否是必填
function isRequireLinkId(linkType){
    console.log(linkType);
    //var arr = ['41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52'];
    /*var arr = [41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52];
    if ($.inArray(linkType, arr)) {
        return true;
    }*/
    if (linkType == 41 || linkType == 42 || linkType == 43 || linkType == 44 || linkType == 45 || linkType == 46 || linkType == 47 || linkType == 48 || linkType == 49 || linkType == 50 || linkType == 51 || linkType == 52) {
        return true;
    }

    return false;
}